//定义依赖和插件
var gulp = require('gulp'),
    uglify = require('gulp-uglify'),
    concat = require('gulp-concat'),
    rename = require('gulp-rename'),
    connect = require('gulp-connect'),//livereload
    sourcemaps = require('gulp-sourcemaps'),
    less = require('gulp-less'),
    cssmin = require('gulp-minify-css'),
    //当发生异常时提示错误不终止watch时间， 确保本地安装gulp-notify和gulp-plumber
    notify = require('gulp-notify'),
    plumber = require('gulp-plumber'),
    spritesmith = require("gulp.spritesmith"),
    autoprefixer = require('gulp-autoprefixer');

var jsSrc = 'src/js/*.js';
var jsDist = 'dist/js';

var cssSrc = 'src/css/*.js';
var cssDist = 'dist/css';

var lessSrc = ['src/less/*.less','src/less/sprite/*.less','!src/less/back2Top.less'];
var lessDist = 'dist/css';

var htmlSrc = 'src/*.html';
var htmlDist = 'dist';

// 编译less为css
gulp.task('less', function () {
    gulp.src(lessSrc)
        .pipe(sourcemaps.init())
        .pipe(less())
        .pipe(plumber({errorHandler: notify.onError('Error: <%= error.message %>')}))
        .pipe(sourcemaps.write())
        .pipe(autoprefixer({
            browsers: ['last 20 versions', 'Android >= 4.0'],
            cascade: true, //是否美化属性值 默认：true 像这样：
            //-webkit-transform: rotate(45deg);
            //        transform: rotate(45deg);
            remove:true //是否去掉不必要的前缀 默认：true 
        }))
        .pipe(gulp.dest(lessDist))
        .pipe(connect.reload());
});

//定义名为js的任务
gulp.task('js', function () {
    gulp.src(jsSrc)
        .pipe(concat('common.js'))
        .pipe(gulp.dest(jsDist))
        .pipe(rename({suffix: '.min'}))
        .pipe(uglify())
        .pipe(gulp.dest(jsDist))
        .pipe(connect.reload())
});

//定义html任务
gulp.task('html', function () {
    gulp.src(htmlSrc)
        .pipe(gulp.dest(htmlDist))
        .pipe(connect.reload());
});

// 打包sprite图
gulp.task('spritesmith', function() {
    var spritesData = gulp.src('./src/img/sprites/*.png') //需要合并的图片地址
        .pipe(spritesmith({
            imgName: 'sprites.png', //保存合并后图片的地址
            cssName: 'sprites.less', //保存合并后对于css样式的地址
            imgPath: '../imgs/sprites/sprites.png',
            padding: 5, //合并时两个图片的间距
            algorithm: 'top-down'
        }));
    spritesData.img.pipe(gulp.dest('dist/imgs/sprites/'));
    spritesData.css.pipe(gulp.dest('src/less/sprites/'));
});

//定义livereload任务
gulp.task('connect', function () {
    connect.server({
        livereload: true
    });
});


//定义守护进程
gulp.task('watch', function () {

    gulp.watch('src/*.html', ['html']);

    // gulp.watch('src/js/*.js', ['js']);

    gulp.watch('src/less/*.less', ['less']);
});

//定义默认任务
gulp.task('prod', [ 'js', 'html', 'spritesmith', 'less', 'watch', 'connect']);

gulp.task('default', [ 'html', 'spritesmith', 'less', 'watch', 'connect']);